$(function() {

	var teamList;
	var wayConfig = {
		'飞机':'航班',
		'火车':'车次',
		'轮船':'船次',
		'自驾':'备注',
		'其他':'备注'
	};
	var travelCitys = [
		'莫斯科', '圣彼得堡', '下诺夫哥罗德', '叶卡捷琳堡', '索契', '加里宁格勒', '喀山',
		'萨马拉', '萨兰斯克', '伏尔加格勒', '顿河畔罗斯托夫', '苏兹达尔', '弗拉基米尔',
		'科斯特罗马', '雅罗斯拉夫尔', '谢尔盖耶夫镇', '大罗斯托夫', '伊万诺沃', '佩列斯拉夫尔-扎列斯基',
		'贝加尔湖', '伊尔茨库克',
		'海参崴', '摩尔曼斯克', '布里亚特', '新西伯利亚', '哈巴罗夫斯克', '利斯特维扬卡', '海兰泡', 
		'奥尔洪岛', '克拉斯诺达尔', '沃罗涅日', '芬兰', '瑞典', '挪威', '丹麦', '乌克兰', '白俄罗斯', 
		'拉脱维亚', '立陶宛', '爱沙尼亚', '波兰'
	];
	var gameList = [];
	var param = parseUrlSearch();
	var cache = null;

	$.init();

	if(param.edit) {
		fetchSelfInfo(backFill);
	}else{
		fetchWxSeflInfo(backFill);
	}

	createSelect({
		wrapper: '.info-sex input',
		title: '性别',
		list: ['男', '女'],
		values: []
	});
	createSelect({
		wrapper: '.watch-vehicle input',
		title: '出行方式',
		list: Object.keys(wayConfig),
		onClose: appendWatchVehicleInput
	});

	function backFill(data) {
		cache = data;

		$('.info-name input').val(data.name||'');
		$('.info-wx input').val(data.wxid||'');
		$('.info-sex input').val(['','男','女'][data.gender]||'');
		$('.info-age input').val(formatDate(data.birthYear)||'');
		$('.info-peer input').val(data.peerNum||'');
		if(data.labels && data.labels.length) {
			$('.info-tag input').val(data.labels.join('&'));
		}
		$('.info-desc textarea').val(data.description||'');
		if(data.supportTeams && data.supportTeams.length) {
			$('.info-team .text').html(data.supportTeams.toString());
		}
		$('.watch-from input').val(data.fromCity||'');
		$('.watch-to input').val(data.toCity||'');
		$('.watch-startdate input').val(data.startDate||'');
		$('.watch-returndate input').val(data.returnDate||'');
		if(data.matches && data.matches.length) {
			$('.watch-game .text').html(data.matches.toString());
		}
		$('.watch-vehicle input').val(data.vehicle||'');

		if(wayConfig[data.vehicle]) {
			appendWatchVehicleInput();
			$('.watch-vehicleNo input').val(data.vehicleNo||'');
		}
		if(data.travels && data.travels.length > 0) {
			data.travels.forEach(function(item, index) {
				addTravel();
				var $travel = $('.travel'+ (index + 1));
				if(travelCitys.indexOf(item.city) == -1) {
					appendTravelOtherInput(index + 1);
					$('.travel-otherCity input', $travel).val(item.city||'');
					$('.travel-city input', $travel).val('其他');
				}else{
					$('.travel-city input', $travel).val(item.city||'');
				}
				$('.travel-start input', $travel).val(item.startDate||'');
				$('.travel-end input', $travel).val(item.endDate||'');
				$('.travel-vehicle input', $travel).val(item.vehicle||'');
				if(wayConfig[item.vehicle]) {
					appendTravelVehicleInput(index+1);
					$('.travel-vehicleNo input', $travel).val(item.vehicleNo||'');
				}
				$('.travel-hotelReserve input', $travel).val(['未预定','预定'][item.hotel]||'');
				if(item.hotel == '已预订') {
					$('.travel-hotelReserve', $travel).after(getHotelInfoHtml());
				}
				$('.travel-hotel input', $travel).val(item.hotelName||'');
			});
		}
		createCalendar({
			$wrapper: $('.info-age input'),
			value: data.birthYear ? [formatDate(data.birthYear)] : ['2000-01-01']
		});
		createCalendar({
			$wrapper: $('.watch-startdate input'),
			value: data.startDate ? [data.startDate] : [moment().format('YYYY-MM-DD')]
		});
		createCalendar({
			$wrapper: $('.watch-returndate input'),
			value: data.returnDate ? [data.returnDate] : [moment().format('YYYY-MM-DD')]
		});
		renderTeams();
		renderTags();
		renderMatches();
	}

	function formatDate(data) {
		if(!data) {
			return '';
		}
		if(typeof data == 'number') {
			data = data + '';
			return data.slice(0,4)+'-'+data.slice(4,6)+'-'+data.slice(6);
		}else{
			return data.replace(/\-/g, '');
		}
	}

	function renderTeams() {
		fetchTeams(function(list) {
			var html = '';
			list.forEach(function(item) {
				var isIn = false;
				if(cache && cache.supportTeams) {
					isIn = cache.supportTeams.indexOf(item) > -1;
				}
				html += '<span class="button button-round '+(isIn?'button-fill':'button-dark')+'" data-value="'+item+'">'+item+'</span>';
			});
			$('#router1 .tab-list').html(html);
		});
	}

	function renderTags() {
		var html = '';
		var labels = ['追求完美','元气满满','文艺青年','善解人意','风流倜傥','多愁善感','大智若愚','直觉惊人','捉摸不透',
			'足智多谋','外冷内热','健身狂魔','一表人才','温文尔雅','王者风范','逻辑清晰','重视原则',
			'心思敏捷','相当执着','沟通力满分','霸道总裁','风趣幽默','爱恨分明','个性稳重','精力充沛','任劳任怨',
			'低调含蓄','思想前卫','重色轻友','深谋远虑','通情达理','多重人格','实事求是','小心谨慎','仗义执言',
			'铁面无私','无微不至','乐于助人','上进心强','持之以恒','狂放不羁','温柔体贴','不善交际','老实憨厚'];
		var stars = ["梅西", "C.罗纳尔多", "内马尔", "莱万多夫斯基", "托尼·克罗斯", "A.桑切斯", "坎特", "阿扎尔", 
			"德布劳内", "卢卡库", "哈里·凯恩", "卡瓦尼", "奥巴梅扬", "诺伊尔", "蒂亚戈", "路易斯·苏亚雷斯", 
			"莫德里奇", "马塞洛", "塞尔吉奥·拉莫斯", "哲科", "拉卡泽蒂", "阿斯皮利奎塔", "迭戈·科斯塔", 
			"大卫·路易斯", "阿奎罗", "德赫亚", "伊斯科", "奥布拉克", "格列兹曼", "费利佩·路易斯", "戈丁", 
			"毛罗·伊卡尔迪", "迪巴拉", "阿莱克斯·桑德罗", "冈萨罗·伊瓜因", "布冯", "A. 贝洛提", "穆斯塔菲", 
			"科斯切尔尼", "萨拉赫", "库蒂尼奥", "撒迪奥·马内", "席尔瓦", "奥塔门迪", "保罗·博格巴", "范迪克", 
			"D.阿里", "克里斯蒂安·埃里克森", "法尔考", "姆巴佩"];
		labels = labels.concat(stars);
		labels.forEach(function(label) {
			var isIn = false;
			if(cache && cache.labels) {
				isIn = cache.labels.indexOf(label) > -1;
			}
			html += '<span class="button button-round '+(isIn?'button-fill':'button-dark')+'" data-value="'+label+'">'+label+'</span>';
		});
		$('#router2 .tab-list').html(html);
	}

	function renderMatches() {
		fetchMatches(function(list) {
			var html = '';
			list.forEach(function(item) {
				var isIn = false;
				if(cache && cache.matches) {
					isIn = cache.matches.indexOf(item.id) > -1;
				}
				html += '<span class="button button-round '+(isIn?'button-fill':'button-dark')+'" data-value="'+item.id+'">'+item.id+'('+( item.homeTeam + 'vs' + item.awayTeam)+')</span>';
			});
			$('#router3 .tab-list').html(html);
		});
	}

	function fetchSelfInfo(callback) {
		$.ajax({
			type: 'GET',
			url: HOST + '/api/travel/get?openid=' + SELFID,
			success: function(data) {
				callback && callback(data);
			}
		});
	}

	function fetchWxSeflInfo(callback) {
		$.ajax({
			type: 'GET',
			url: HOST + '/api/user/get?openid=' + SELFID,
			success: function(data) {
				var content = data.content;
				callback && callback({
					name: content.wxname,
					wxid: content.wxid
				});
			}
		});
	}

	function createAreaSelect(options) {
		$(options.wrapper).cityPicker({
			toolbarTemplate: '<header class="bar bar-nav">\
				<button class="button button-link pull-right close-picker">确定</button>\
				<h1 class="title">选择出发城市</h1>\
				</header>'
		});
	}

	function fetchMatches(callback) {
		$.ajax({
			type: 'GET',
			url: HOST + '/api/game/list',
			success: function(res) {
				callback && callback(res.content);
			}
		});
	}

	function fetchTeams(callback) {
		$.ajax({
			type: 'GET',
			url: HOST + '/api/game/listTeam',
			success: function(res) {
				callback && callback(res.content);
			}
		});
	}

	function appendWatchVehicleInput() {
		$('.watch-vehicleNo').remove();
		if($('.watch-vehicleNo').length !== 1) {
			var way = $('.watch-vehicle input').val();
			var html = getVehicleInputHtml(way, 'watch');
			$('.watch-vehicle').after(html);
		}
	}

	function appendTravelVehicleInput(id) {
		$('.travel'+id+' .travel-vehicleNo').remove();
		if($('.travel'+id+' .travel-vehicleNo').length !== 1) {
			var way = $('.travel'+id+' .travel-vehicle input').val();
			var html = getVehicleInputHtml(way, 'travel');
			$('.travel'+id+' .travel-vehicle').after(html);
		}
	}

	function appendTravelOtherInput(id) {
		if($('.travel'+id+' .travel-otherCity').length == 0) {
			var html = getTravelCityHtml();
			$('.travel'+id+' .travel-city').after(html);
		}
	}

	/* 注册事件*/
	$('.j-submit').on('click', submitHandle);
	$('.j-add').on('click', addTravel);
	$('.j-del').on('click', delTravel);
	$('.j-return').on('click', returnPage);
	$(document).on('click', '#router1 .pull-right', backFromTeam);
	$(document).on('click', '#router2 .pull-right', backFromLabel);
	$(document).on('click', '#router3 .pull-right', backFromMatch);
	$(document).on('click', '.router-return', returnBack);
	$(document).on('click', '.tab-list', toggleButton);
	$(document).on('focus', '.info-wx input', function() {
		$('.info-wx').addClass('info-withtip');
	});
	$(document).on('blur', '.info-wx input', function() {
		$('.info-wx').removeClass('info-withtip');
	});

	function returnBack(e) {
		var $box = $(e.target).closest('.page');
		var id = $box.attr('id');
		var values = '';
		if(id == 'router1') {
			values = $('.info-team .item-input .text').html();
		}else if(id == 'router2') {
			values = $('.info-tag .item-input .text').html();
		}else if(id == 'router3') {
			values = $('.watch-game .item-input .text').html();
		}
		if(/\<em\>/.test(values)) {
			$('.button', $box).removeClass('button-fill').addClass('button-dark');
		}else{
			values = values.split(',');
			$('.tab-list .button', $box).each(function(index, item) {
				var $item = $(item);
				if(values.indexOf($item.data('value')) > -1) {
					$item.addClass('button-fill').removeClass('button-dark');
				}else{
					$item.addClass('button-dark').removeClass('button-fill');
				}
			});
		}
	}

	function backFromTeam(e) {
		var val = '';
		$('#router1 .tab-list .button-fill').each(function() {
			var $btn = $(this);
			val += ($btn.data('value') + ',');
		});
		$('.info-team .item-input .text').html(val.slice(0,-1) || '<em>请选择球队</em>');
	}

	function backFromLabel(e) {
		var val = '';
		$('#router2 .tab-list .button-fill').each(function() {
			var $btn = $(this);
			val += ($btn.data('value') + ',');
		});
		$('.info-tag .item-input .text').html(val.slice(0,-1) || '<em>请选择标签</em>');
	}

	function backFromMatch() {
		var val = '';
		$('#router3 .tab-list .button-fill').each(function() {
			var $btn = $(this);
			val += ($btn.data('value') + ',');
		});
		$('.watch-game .item-input .text').html(val.slice(0,-1) || '<em>请选择观看比赛</em>');
	}

	function toggleButton(e) {
		var $target = $(e.target);
		if($('#router1 .button-fill').length > 2 && !$target.hasClass('button-fill')) {
			if($('#router1').hasClass('page-current')) {
				$.alert('最多选择3个球队！');
				return;
			}
		}
		if($('#router2 .button-fill').length > 2 && !$target.hasClass('button-fill')) {
			if($('#router2').hasClass('page-current')) {
				$.alert('最多选择3个标签！');
				return;
			}
		}
		if($target.hasClass('button')) {
			$target.toggleClass('button-dark button-fill');
		}
	}

	function returnPage() {
		if(param.edit) {
			window.location = './travel_info.html';
		}else{
			window.location = HOST + '/index.html';
		}
	}


	function submitHandle() {
		var data = getSubmitData();
		var error = validate(data);
		// console.log(data);
		if(error) {
			$.alert(error);
			return;
		}
		$.showPreloader('保存中，请稍等');
		$.ajax({
			type: 'post',
			url: HOST + '/api/travel/'+(param.edit?'update':'insert'),
			data: JSON.stringify(data),
			success: function(res) {
				if(res.content == 'success') {
					if(param.edit) {
						window.location = ('./travel_info.html');
					}else{
						window.location = ('./travel_list.html');
					}
					return;
				}
				$.hidePreloader();
				$.alert('保存失败喽，请联系管理员');
			}
		});
	}

	function getSubmitData(){
		var result = {};
		result.openid = SELFID;
		result.name = $('.info-name input').val();
		result.wxid = $('.info-wx input').val();
		result.gender = {'男':1,'女':2}[$('.info-sex input').val()];
		result.birthYear = $('.info-age input').val();
		result.age = jsGetAge(result.birthYear);
		result.birthYear = formatDate(result.birthYear);
		var teams = $('.info-team .text').html();
		result.supportTeams = /\<em\>/g.test(teams) ? [] : teams.split(',');
		result.peerNum = $('.info-peer input').val();
		var labels = $('.info-tag .text').html();
		result.labels = /\<em\>/g.test(labels) ? [] : labels.split(',');
		result.description = $('.info-desc textarea').val();
		result.fromCity = $('.watch-from input').val();
		result.toCity = $('.watch-to input').val();
		result.startDate = $('.watch-startdate input').val();
		result.returnDate = $('.watch-returndate input').val();
		var matches = $('.watch-game .text').html();
		result.matches = /\<em\>/g.test(matches) ? [] : matches.split(',');
		result.vehicle = $('.watch-vehicle input').val();
		result.vehicleNo = $('.watch-vehicleNo input').val();
		result.travels = [];
		$('.list-block-travel').each(function(index, item) {
			var $item = $(this);
			var city = $('.travel-city input', $item).val();
			result.travels.push({
				"city": city == '其他' ? $('.travel-otherCity input', $item).val() : city,
            	"startDate": $('.travel-start input', $item).val(),
            	"endDate": $('.travel-end input', $item).val(),
            	"vehicle": $('.travel-vehicle input', $item).val(),
            	"vehicleNo": $('.travel-vehicleNo input', $item).val(),
            	"hotel": {'预定':1,'未预定':0}[$('.travel-hotelReserve input', $item).val()],
            	"hotelName": $('.travel-hotelName input', $item).val()
			});
		});
		return result;
	}

	function validate(data) {
		if(!data.name || !data.wxid || !data.gender || !data.birthYear || !data.peerNum) {
			return '基本信息有未填写项!'
		}
		if(!data.fromCity || !data.toCity || !data.startDate || !data.returnDate || !data.vehicle) {
			return '观赛信息有未填写项!';
		}
		if(compareDate(data.startDate, data.returnDate) == 3) {
			return '出发日期不允许大于返程日期!';
		}
		for(var i = 0; i < data.travels.length; i++){
			var item = data.travels[i];
			if(!item.city || !item.startDate || !item.endDate || !item.vehicle || item.hotel === '') {
				return '旅游信息有未填写项!';
			}
			if(compareDate(item.startDate, item.endDate) == 3) {
				return '出发日期不允许大于返程日期!';
			}
		}
		return '';
	}

	function addTravel() {
		var id = $('.list-block-travel').length + 1;
		$('.add-area').before(getTravelInfoHtml(id));
		var $travel = $('.travel'+id);
		createCalendar({
			$wrapper: $travel.find('.travel-start input'),
			value: [moment().format('YYYY-MM-DD')]
		});
		createCalendar({
			$wrapper: $travel.find('.travel-end input'),
			value: [moment().format('YYYY-MM-DD')]
		});
		createSelect({
			wrapper: '.travel'+id+' .travel-vehicle input',
			title: '出行方式',
			list: Object.keys(wayConfig),
			onClose: function(){
				appendTravelVehicleInput(id);
			}
		});
		createSelect({
			wrapper: '.travel'+id+' .travel-hotelReserve input',
			title: '酒店预订',
			list: ['未预定', '已预定'],
			onClose: function(){
				if($('.travel-hotelReserve input', $travel).val() == '已预定'){
					if($('.travel-hotelName',$travel).length == 0) {
						$('.travel-hotelReserve', $travel).after(getHotelInfoHtml());
					}
				}else{
					$('.travel-hotelName', $travel).remove();
				}
			}
		});
		createSelect({
			wrapper: '.travel'+id+' .travel-city input',
			list: travelCitys.concat('其他'),
			title: '选择旅游城市',
			onClose: function(){
				if(arguments[0].value == '其他') {
					appendTravelOtherInput(id);	
				}else{
					$('.travel-otherCity', $travel).remove();
				}
			}
		});
		$('.j-del').off();
		$('.j-del').on('click', delTravel);
	}

	function delTravel(e) {
		$(e.currentTarget).closest('.list-block').remove();
	}

	function getTravelInfoHtml(id) {
		return [
			'<div class="list-block my-list-block list-block-travel travel'+id+'">',
				'<div class="group-title">景点旅游</div>',
				'<ul class="card">',
					'<li class="travel-city"><div class="item-content"><div class="item-media"><i class="icon icon-form-name">*</i></div><div class="item-inner"><div class="item-title label">旅游地点</div><div class="item-input"><input type="text" placeholder="请选择旅游地点"></div></div></div></li>',
					'<li class="travel-start"><div class="item-content"><div class="item-media"><i class="icon icon-form-name">*</i></div><div class="item-inner"><div class="item-title label">出发日期</div><div class="item-input"><input type="text" placeholder="请选择出发日期" data-toggle="date" readonly></div></div></div></li>',
					'<li class="travel-end"><div class="item-content"><div class="item-media"><i class="icon icon-form-name">*</i></div><div class="item-inner"><div class="item-title label">返程日期</div><div class="item-input"><input type="text" placeholder="请选择返程日期" data-toggle="date" readonly></div></div></div></li>',
					'<li class="travel-vehicle"><div class="item-content"><div class="item-media"><i class="icon icon-form-name">*</i></div><div class="item-inner"><div class="item-title label">出行方式</div><div class="item-input"><input type="text" placeholder="请输入出行方式"></div></div></div></li>',
					'<li class="travel-hotelReserve"><div class="item-content"><div class="item-media"><i class="icon icon-form-name">*</i></div><div class="item-inner"><div class="item-title label">酒店预订</div><div class="item-input"><input type="text" placeholder="请输入酒店预订"></div></div></div></li>',
					'<li class="btn-del"><a href="javascript:;" class="j-del">删除此行程</a></li>',
				'</ul>',
			'</div>'
		].join('');
	}

	function getTeamInputHtml(id) {
		return '<li  class="info-team team'+id+'">\
        			<div class="item-content">\
						<div class="item-media"><i class="icon icon-form-name">&nbsp;</i></div>\
						<div class="item-inner">\
							<div class="item-title label">球队'+id+'</div>\
							<div class="item-input">\
								<input type="text" placeholder="请选择支持球队" readonly>\
							</div>\
						</div>\
					</div>\
        		</li>';
	}

	function getGameInputHtml(id) {
		return '<li class="watch-game watch-game'+id+'">\
        			<div class="item-content">\
						<div class="item-media"><i class="icon icon-form-name">&nbsp;</i></div>\
						<div class="item-inner">\
							<div class="item-title label">观看比赛'+id+'</div>\
							<div class="item-input">\
								<input type="text" placeholder="请选择观看比赛" readonly>\
							</div>\
						</div>\
					</div>\
        		</li>'
	}

	function getVehicleInputHtml(way, type) {
		var label = wayConfig[way];
		return '<li class="'+type+'-vehicleNo">\
        			<div class="item-content">\
						<div class="item-media"><i class="icon icon-form-name">&nbsp;</i></div>\
						<div class="item-inner">\
							<div class="item-title label">'+label+'</div>\
							<div class="item-input">\
								<input type="text" placeholder="请输入'+label+'">\
							</div>\
						</div>\
					</div>\
        		</li>';
	}

	function getHotelInfoHtml() {
		return '<li class="travel-hotelName"><div class="item-content"><div class="item-media"><i class="icon icon-form-name">&nbsp;</i></div><div class="item-inner"><div class="item-title label">酒店信息</div><div class="item-input"><input type="text" placeholder="请输入酒店名称或其他"></div></div></div></li>'
	}

	function getTravelCityHtml() {
		return '<li class="travel-otherCity"><div class="item-content"><div class="item-media"><i class="icon icon-form-name">&nbsp;</i></div><div class="item-inner"><div class="item-title label">其他</div><div class="item-input"><input type="text" placeholder="请输入旅游地点"></div></div></div></li>'
	}
})
